<template>
  <div class="outer-container">
    <div class="main-container">
      <el-card class="form-card">
        <el-form>
          <el-form-item>
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :show-file-list="true"
              :limit="1"
              accept=".json"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传1个 JSON 文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item class="model-and-button-row">
            <div class="left-aligned">
              <el-select v-model="selectedModel" placeholder="请选择模型">
                <el-option
                  v-for="model in availableModels"
                  :key="model"
                  :label="model"
                  :value="model"
                  :disabled="testedModels.includes(model)"
                />
              </el-select>
            </div>
            <div class="right-aligned">
              <el-button type="primary" @click="testModel" :loading="isTesting">开始测试</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
      <div id="chart" class="chart-container" v-loading="isTesting">
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const availableModels = ref(['BART_NLPCC', 'BART_WEIBO', 'T5']);
const selectedModel = ref('');
const file = ref(null);
const testResults = ref([]);
const isTesting = ref(false); // 新增加载状态变量
const testedModels = ref([]); // 记录已测试的模型

const handleFileChange = (uploadFile) => {
  file.value = uploadFile.raw;
  testResults.value = [];
  testedModels.value = [];
  selectedModel.value = '';

  // 清除图表
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
};

const beforeUpload = (uploadFile) => {
  const isJson = uploadFile.type === 'application/json';
  if (!isJson) {
    ElMessage.error('请上传 JSON 文件');
  }
  return isJson;
};

const testModel = async () => {
  if (!file.value) {
    ElMessage.error('请上传 JSON 文件');
    return;
  }
  if (!selectedModel.value) {
    ElMessage.error('请选择模型');
    return;
  }
  if (testedModels.value.includes(selectedModel.value)) {
    ElMessage.warning('该模型已经测试过，不可再次测试');
    return;
  }
  isTesting.value = true; // 开始测试，设置加载状态为 true

  try {
    const formData = new FormData();
    formData.append('file', file.value);
    formData.append('model', selectedModel.value);

    const response = await axios.post('http://127.0.0.1:5000/summarize_json', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    const { "rouge-1": rouge1, "rouge-2": rouge2, "rouge-l": rougeL, loss_avg: loss } = response.data;
    testResults.value.push({
      model: selectedModel.value,
      rouge1,
      rouge2,
      rougeL,
      loss
    });
    testedModels.value.push(selectedModel.value); // 将已测试的模型添加到数组中
    drawChart();
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求出错，请检查网络或后端服务');
  } finally {
    isTesting.value = false; // 测试结束，设置加载状态为 false
  }
};

const drawChart = () => {
  const xData = testResults.value.map(result => result.model);
  const rouge1Data = testResults.value.map(result => result.rouge1);
  const rouge2Data = testResults.value.map(result => result.rouge2);
  const rougeLData = testResults.value.map(result => result.rougeL);
  const lossData = testResults.value.map(result => result.loss);

  const chartDom = document.getElementById('chart');
  const myChart = echarts.init(chartDom);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: 'ROUGE-1',
        type: 'bar',
        data: rouge1Data
      },
      {
        name: 'ROUGE-2',
        type: 'bar',
        data: rouge2Data
      },
      {
        name: 'ROUGE-L',
        type: 'bar',
        data: rougeLData
      },
      {
        name: '平均损失值',
        type: 'bar',
        data: lossData
      }
    ]
  };

  myChart.setOption(option);

  // 监听窗口大小变化，调整图表大小
  const resizeChart = () => {
    myChart.resize();
  };
  window.addEventListener('resize', resizeChart);

  // 组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener('resize', resizeChart);
  });
};

</script>

<style scoped>
.outer-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  height: 78vh;
  max-height: 78vh;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow-y: auto;
  margin-top: 40px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.main-container {
  padding: 20px;
}

.form-card {
  margin-bottom: 1px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.upload-demo {
  width: 100%;
  border: 2px dashed #ccc;
  border-radius: 5px;
  padding: 20px;
  text-align: center;
  transition: border-color 0.3s;
}

.upload-demo:hover {
  border-color: #409eff;
}

.el-upload__text {
  margin-top: 10px;
  font-size: 14px;
}

.el-upload__tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

.chart-container {
  background-color: rgb(238, 241, 245);
  margin: 20px 0;
  min-height: 50vh;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  position: relative;
}

.model-and-button-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-aligned {
  flex: 1;
}

.right-aligned {
  flex-shrink: 0;
}
</style>